package com.fhc.base

import android.app.ApplicationErrorReport
import android.content.Context
import android.content.Intent
import android.widget.Toast
import androidx.core.content.ContextCompat.startActivity
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber
import java.io.PrintWriter
import java.io.StringWriter
import kotlin.coroutines.CoroutineContext
import kotlin.system.exitProcess

const val CRASH_INFO = "UncaughtExceptionHandler"

//        Application onCreate()
//        val oldHandler = Thread.getDefaultUncaughtExceptionHandler()
//        Thread.setDefaultUncaughtExceptionHandler(CrashHandler(applicationContext, oldHandler))


 fun restartApp(context: Context, mainActivity: Class<*>, crashInfo: String) {
    val intent = Intent(context, mainActivity).apply {
        flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        putExtra(CRASH_INFO, crashInfo)
    }
    context.startActivity(intent)
    android.os.Process.killProcess(android.os.Process.myPid())
    exitProcess(1)
}

/**
 * Crash handler
 *
 * @property context
 * @property oldHandler
 * @constructor Create empty Crash handler
 */
class CrashHandler(
    private val context: Context,
    private val oldHandler: Thread.UncaughtExceptionHandler?,
    private val onCrash: ((Throwable) -> Unit)?

) : Thread.UncaughtExceptionHandler {

    override fun uncaughtException(thread: Thread, exception: Throwable) {

        // 1. 记录异常日志
        Timber.e(exception, "Uncaught exception in ${thread.name}")

        // 2. 获取完整堆栈信息
        val stackTrace = StringWriter().apply {
            exception.printStackTrace(PrintWriter(this))
        }.toString()

        // 3. 执行回调（可用于上报崩溃等操作）
        onCrash?.invoke(exception)
        if (onCrash == null) {
                Timber.e(stackTrace)

                // 4. 显示用户友好提示
                CoroutineScope(Dispatchers.Main).launch {
                    Toast.makeText(
                        context,
                        exception.message?.takeIf { it.isNotBlank() } ?: "Unknown error occurred",
                        Toast.LENGTH_LONG
                    ).show()
                }

        }

        Toast.makeText(context,exception.message?.ifNoValue { "Unknown error!" }, Toast.LENGTH_SHORT).show()
//        Intent(context.applicationContext, ErrorActivity::class.java).apply {
//            putExtra(ErrorActivity.EXTRA_ERROR_MESSAGE, exception.message?.ifNullOrEmpty { "Unknown error!" })
//            putExtra(ErrorActivity.EXTRA_STACK_TRACE, stackTrace.toString())
//            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//        }.also { context.applicationContext.startActivity(it) }

        oldHandler?.uncaughtException(thread, exception) ?: exitProcess(2)
    }
}

class GlobalCoroutineExceptionHandler : CoroutineExceptionHandler {
    override val key: CoroutineContext.Key<*> get() = CoroutineExceptionHandler

    override fun handleException(context: CoroutineContext, exception: Throwable) {
        // 全局异常处理逻辑
        Timber.e(exception)
        // 可以上报 Crash 或者发送事件给 UI 层提示用户
    }
}